package mysql

import (
	"gorm.io/gorm"
	"manuscript-service/manuscriptrpc/manuscriptrpc"
)

type Manuscript struct {
	gorm.Model
	Title   string `gorm:"type:varchar(50);not null;comment:'标题'"`
	Author  string `gorm:"type:varchar(50);not null;comment:'作者'"`
	Content string `gorm:"type:varchar(255);not null;comment:'内容'"`
	ClassId int64  `gorm:"type:int(11);not null;comment:'分类ID'"`
}

func (m *Manuscript) ManuscriptAdd(db *gorm.DB) error {
	return db.Debug().Create(m).Error
}

func (m *Manuscript) ManuscriptFindByTitle(db *gorm.DB, title string) error {
	return db.Debug().Where("title=?", title).First(m).Error
}

func ManuscriptList(db *gorm.DB, list []*manuscriptrpc.ManuscriptList) []*manuscriptrpc.ManuscriptList {
	db.Debug().Model(&Manuscript{}).
		Select(
			"manuscripts.id as manuscript_id",
			"manuscripts.title",
			"manuscripts.author",
			"manuscripts.content",
			"manuscripts.created_at",
			"classes.`name` as class_name").
		Joins("LEFT JOIN classes ON manuscripts.class_id = classes.id").
		Find(&list)
	return list
}
